import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;


public class DownLoadFile {

	/**
	 * generate file name, eliminate non-filename charater in url
	 * @param url The url waiting to be handled.
	 * @param contentType The contenttype of this url.
	 * @return
	 */
	public String getFileNameByUrl(String url, String contentType) {
		//remove http
		url = url.substring(7);
		//text/html
		if(url.indexOf("html") != -1) {
			url = url.replaceAll("[\\?/:*|<>\"]", "_");
			return url;
		} else {
			return url.replaceAll("[\\?/:*|<>\"]", "_") + "." + 
					contentType.substring(contentType.lastIndexOf("/") + 1, contentType.lastIndexOf(";"));
		}
	}
	
	/**
	 * save byte of web page to local.
	 * @param data The data to be saved.
	 * @param filePath The path which data will be saved.
	 */
	private void saveToLocal(byte[] data, String filePath) {
		try {
			DataOutputStream out = new DataOutputStream(new FileOutputStream(new File(filePath)));
			for (int i = 0; i < data.length; i++) {
				out.write(data[i]);
			}
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * download page
	 * @param url The url should be downloaded.
	 * @return the filePath of the web page.
	 */
	public String downloadFIle(String url) {
		String filePath = null;

		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(url);
		HttpResponse response;
		try {
			response = httpclient.execute(httpget);
			if(response.getStatusLine().getStatusCode() != 200) {
				System.err.println("Method failed: " + response.getStatusLine());
				filePath = null;
			}
			HttpEntity entity = response.getEntity();
			if (entity != null) {
			    InputStream instream = entity.getContent();
			    filePath = "tmp\\" + getFileNameByUrl(url, entity.getContentType().getValue());
			    String charset = response.getParams().getParameter(
		                CoreProtocolPNames.HTTP_CONTENT_CHARSET).toString();
			    System.out.println(entity.getContentType().getValue());
			    System.out.println(filePath);
			    File file = new File(filePath);
			    OutputStream wf = new FileOutputStream(file);
			    try {
			    	copyStream(instream, wf, charset);
			    	instream.close();
			    	wf.close();
			    } finally {
			        instream.close();
			        wf.close();
			    }
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return filePath;
	}
	
	/**
     * 
     * @throws IOException
     */
    public void copyStream(InputStream is, OutputStream os, String charset) throws IOException {
        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, charset));
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(os, charset));
        line = reader.readLine();
        while (line != null) {
            writer.println(line);
            line = reader.readLine();
        }
        writer.flush();
    }
}
